//
//  HEGoodsMenuView.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/2.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEGoodsMenuView.h"
#import "HEGoodsMenuModel.h"
#import "HEFilterBottomView.h"
#import "HEMenuItemCell.h"
#import "TableViewHeaderView.h"
#import "HEMenuPriceRangeCell.h"

static NSString *const KCellItemId = @"HEMenuItemCell";
static NSString *const KCellPriceId = @"HEMenuPriceRangeCell";

@interface HEGoodsMenuView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray <HEGoodsMenuModel *> *titleModels;
@property (nonatomic, strong) NSMutableArray <QMUIButton *> *btnArr;
@property (nonatomic, assign) BOOL showInWindow;             //下拉列表展示在window上，以应对列表视图展示的问题（默认NO）
@property (nonatomic, strong) UIView *backGroundView;
@property (nonatomic, assign) CGFloat maxHeight;
@property (nonatomic, assign) CGFloat inWindowMinY;
@property (nonatomic, assign) BOOL isShow;//是否展开
@property (nonatomic, strong) GDTableView *leftTableView;

@property (nonatomic, strong) HEFilterBottomView *bottomView;
@property (nonatomic, assign) NSInteger selectedTabIndex;
@property (nonatomic, strong) UIView *moreView;
@property (nonatomic, strong) NSMutableArray *sections;

@end

@implementation HEGoodsMenuView

- (instancetype)initWithFrame:(CGRect)frame maxHeight:(CGFloat)maxHeight{
    if (self=[super initWithFrame:frame]) {
//        self.backgroundColor = UIColor.orangeColor;
        
        self.qmui_borderPosition = QMUIViewBorderPositionBottom;
        self.qmui_borderWidth = 0.5;
        self.qmui_borderColor = CSplitLineColor;
        self.inWindowMinY = 0;
        self.maxHeight = maxHeight;
        
        self.brandArr = @[].mutableCopy;
        
        self.sections = @[@"品牌", @"价格区间"].mutableCopy;
        
        [self initUI];
    }
    return self;
}

- (void)initUI {
    NSArray *titleArr = @[@"销量",@"价格",@"筛选"];
    NSArray *imageArr = @[@"desc",@"desc",@"selection_normal"];
    _titleModels = @[].mutableCopy;
    _btnArr = @[].mutableCopy;
    
    for (int i=0; i < titleArr.count; i++) {
        QMUIButton *btn = [[QMUIButton alloc] init];
        btn.imagePosition = QMUIButtonImagePositionRight;// 将图片位置改为在文字下方
        btn.tintColorAdjustsTitleAndImage = UIColor.blackColor;
        btn.adjustsImageTintColorAutomatically = NO;
        btn.spacingBetweenImageAndTitle = 10;
        [btn setImage:UIImageMake(imageArr[i]) forState:UIControlStateNormal];
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        btn.titleLabel.font = DYFont(15);
        [self addSubview:btn];
        btn.tag = i;
        [btn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        HEGoodsMenuModel *model = [HEGoodsMenuModel new];
        model.isDesc = YES;
        model.index = i;
        model.titleType = i < 2 ? HEGoodsMenuTitleTypeSort: HEGoodsMenuTitleTypeFilter;
        [_titleModels addObject:model];

        [_btnArr addObject:btn];
    }
    [_btnArr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.height.equalTo(@50);
    }];
    [_btnArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
}

- (void)titleClick:(UIButton *)sender {
    NSInteger tag = sender.tag;
    
    HEGoodsMenuModel *model = _titleModels[tag];
    
    if (model.titleType == HEGoodsMenuTitleTypeFilter) {
        if (self.selectedTabIndex == tag) {
            [self animateMenuViewWithShow:NO];
        }else {
            self.selectedTabIndex = tag;
            [self animateMenuViewWithShow:YES];
        }
    }else {
        
        [self changeMenuTitleImageStatus:model.index];

        if ([_delegate respondsToSelector:@selector(menuView:didSelectSoltAtIndex:isDesc:)]) {
            [_delegate menuView:self didSelectSoltAtIndex:tag isDesc:model.isDesc];
        }
        [self animateMenuViewWithShow:NO];
    }
}

- (void)changeMenuTitleImageStatus:(NSInteger)index {
    QMUIButton *btn = _btnArr[index];
    HEGoodsMenuModel *model = _titleModels[index];
    
    // 重置其他排序
    for (int i = 0 ; i < _btnArr.count - 1; i++) {
        QMUIButton *btn = _btnArr[i];
        HEGoodsMenuModel *model = _titleModels[i];
        if (i != index) {
            model.isDesc = YES;
            [btn setImage:UIImageMake(@"desc") forState:UIControlStateNormal];
        }
    }

    model.isDesc = !model.isDesc;
    if (model.isDesc) {
       [btn setImage:UIImageMake(@"desc") forState:UIControlStateNormal];
    }else {
       [btn setImage:UIImageMake(@"asc") forState:UIControlStateNormal];
    }
}


/** 筛选视图显示&关闭 */
- (void)animateMenuViewWithShow:(BOOL)show {
    
    CGRect menuViewFrom = self.frame;
    UIView *superView = self.superview;
    CGFloat leftTabWidth = menuViewFrom.size.width;
    CGFloat viewHeight = 310;
 
    if (self.showInWindow) {
        menuViewFrom.origin = CGPointMake(menuViewFrom.origin.x, self.inWindowMinY);
        superView = kApplication.keyWindow;
    }
    
    if (show) {
        self.backGroundView.frame = CGRectMake(0, CGRectGetMaxY(menuViewFrom), menuViewFrom.size.width, self.maxHeight);
        [self.superview bringSubviewToFront:self];
        [superView addSubview:self.backGroundView];
        
        self.moreView.frame = CGRectMake(menuViewFrom.origin.x, CGRectGetMaxY(menuViewFrom), leftTabWidth, 0);
        [superView addSubview:self.moreView];
        
        self.bottomView.hidden = NO;
        
        [UIView animateWithDuration:0.3 animations:^{
            self.backGroundView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.3f];
            self.moreView.frame = CGRectMake(menuViewFrom.origin.x, CGRectGetMaxY(menuViewFrom), leftTabWidth, viewHeight);
        }];
    }else {
        [UIView animateWithDuration:0.3 animations:^{
            self.backGroundView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.f];
            self.moreView.frame = CGRectMake(self.moreView.frame.origin.x, self.moreView.frame.origin.y, self.moreView.frame.size.width, 0);
            self.bottomView.hidden = YES;
        } completion:^(BOOL finished) {
            self.selectedTabIndex = -1;
            [self.backGroundView removeFromSuperview];
            [self.moreView removeFromSuperview];
        }];
    }
    self.isShow = show;
}

/** 点击背景恢复默认 */
- (void)backGroundViewTappedClick:(UITapGestureRecognizer *)tapGesture
{
    [self hideMenuList];
}

/** 隐藏 */
- (void)hideMenuList
{
    [self animateMenuViewWithShow:NO];
}

#pragma mark -

- (void)setBrandArr:(NSMutableArray<HEBrandModel *> *)brandArr {
    _brandArr = brandArr;
//    [self.leftTableView reloadData];
}


#pragma mark - UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HEMenuItemCell *cell = [tableView dequeueReusableCellWithIdentifier:KCellItemId];
        cell.brandArr = self.brandArr;
        return cell;
    }
    HEMenuPriceRangeCell *cell = [tableView dequeueReusableCellWithIdentifier:KCellPriceId];
    cell.model = _titleModels.lastObject;
     return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CGFloat h = ceilf(self.brandArr.count / 3.0) * 40 + 30;
        return h;
    }else {
        return 60;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    TableViewHeaderView *view = [[TableViewHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
    view.name.text = self.sections[section];
    return view;
}

#pragma mark - lazyloading
- (UITableView *)leftTableView {
    if (!_leftTableView) {
        _leftTableView = [[GDTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _leftTableView.rowHeight = KTableViewCellHeight;
        _leftTableView.dataSource = self;
        _leftTableView.delegate = self;
//        _leftTableView.separatorColor = KLineColor;
//        _leftTableView.separatorInset = UIEdgeInsetsZero;
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _leftTableView.tableFooterView = [[UIView alloc]init];
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.backgroundColor = KWhiteColor;
        
        [_leftTableView registerClass:[HEMenuItemCell class] forCellReuseIdentifier: KCellItemId];
        [_leftTableView registerClass:[HEMenuPriceRangeCell class] forCellReuseIdentifier: KCellPriceId];

    }
    return _leftTableView;
}

- (UIView *)backGroundView
{
    if (!_backGroundView) {
        _backGroundView = [[UIView alloc] init];
        _backGroundView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.f];
        _backGroundView.opaque = NO;
        UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backGroundViewTappedClick:)];
        [_backGroundView addGestureRecognizer:gesture];
    }
    return _backGroundView;
}

- (HEFilterBottomView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[HEFilterBottomView alloc] initBottomViewWithTarget:self resetAction:@selector(resetAction) confirmAction:@selector(confirmAction)];
    }
    return _bottomView;
}

- (UIView *)moreView {
    if (!_moreView) {
        _moreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0)];
        _moreView.clipsToBounds = YES;
        _moreView.backgroundColor = KWhiteColor;
        [self addSubview:_moreView];
        
        self.leftTableView.frame = CGRectMake(0, 0, KScreenWidth, 260);
        [_moreView addSubview:self.leftTableView];
        
        self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(self.leftTableView.frame), KScreenWidth, 50);
        [_moreView addSubview:self.bottomView];
    }
    return _moreView;
}

/** 确定 */
- (void)confirmAction {
    [self animateMenuViewWithShow:NO];
    
    HEGoodsMenuModel *model = _titleModels.lastObject;
    model.selectBrand = @[].mutableCopy;
    for (HEBrandModel *brand in self.brandArr) {
        if (brand.isSelect) {
            [model.selectBrand addObject:[NSNumber numberWithInteger:brand.id]];
        }
    }

    if ([_delegate respondsToSelector:@selector(menuView:didSelectConfirmWithBradIds:minPrice:maxPrice:)]) {
        [_delegate menuView:self didSelectConfirmWithBradIds:[model.selectBrand componentsJoinedByString:@","] minPrice:model.minPrice maxPrice:model.maxPrice];
    }
}

/** 重置 */
- (void)resetAction {
    for (HEBrandModel *model in self.brandArr) {
        model.isSelect = NO;
    }
    HEGoodsMenuModel *model = _titleModels.lastObject;
    model.minPrice = NULL;
    model.maxPrice = NULL;
    [self.leftTableView reloadData];
}



@end
